package com.compress

import java.io.File
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import java.nio.file.Path
import kotlin.io.path.Path
import kotlin.io.path.exists
import kotlin.io.path.pathString
import kotlin.io.path.writeBytes

object PicUtils {

    private val pngquautExt = "pngquant" + if (isWindow()) ".exe" else ""
    private var pngquaut = PicUtils::class.java.classLoader.getResource(pngquautExt)?.path
    private var ext: String? = null

    /**
     * 执行一个文件
     *
     * @param command 命令
     */
    fun exec(vararg command: String?) {
        val processBuilder = ProcessBuilder(*command)
//		pb.directory(new File("cmd"));
        var runningStatus = 0
        var message: String?
        runCatching {
            val process = processBuilder.start()
            val stdInput = process.inputReader()
            val stdError = process.errorReader()
            while (stdInput.readLine().also { message = it } != null) {
                if (message!!.length > 3 && (message!!.startsWith("%n%") || message!!.startsWith("%pro%"))) {
                    print("\r")
                    print(message)
                } else {
                    println(message)
                }
            }
            while (stdError.readLine().also { message = it } != null) {
                System.err.println(message)
            }
            runningStatus = process.waitFor()
        }.onFailure {
            it.printStackTrace()
        }
    }

    /**
     * 根据指定大小和指定精度压缩图片
     *
     * @param srcPath  源图片地址
     * @param accuracy 精度，递归压缩的比率 1-100
     */
    fun commpressPic(srcPath: String, accuracy: String) {
        if (srcPath.isEmpty()) {
            System.err.println("路径不符合要求 = $srcPath")
            return
        }
        if (!File(srcPath).exists()) {
            System.err.println("路径不存在 = $srcPath")
            return
        }
        try {
//            File srcFile = new File(srcPath);
//            long srcFileSize = srcFile.length();
//            System.out.println("源图片：" + srcPath + "，大小：" + srcFileSize / 1024
//                    + "kb");
            val runPath = runPath
            if (ext.equals("jar")) {
                val pngQuautFile = Path(runPath.path, pngquautExt)
                if (!pngQuautFile.exists()) {
                    val stream = PicUtils::class.java.classLoader.getResourceAsStream(pngquautExt)
                    if (stream != null) {
                        val bytes = stream.readAllBytes()
                        pngQuautFile.writeBytes(bytes)
                    }
                }
                pngquaut = pngQuautFile.pathString
                authorization(pngQuautFile)
            }
            exec(
                pngquaut,
                "-f",
                // "-v",
                "--quality=$accuracy",
                "-o", srcPath,
                srcPath
                // , "-h"
            )

//            File desFile = new File(srcPath);
//            System.out.println("目标图片：" + srcPath + "，大小" + desFile.length() / 1024 + "kb");
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取运行路径
     *
     * @return
     */
    val runPath: File
        get() {
            var file: File
            val jar = PicUtils::class.java.getResource("PicUtils.class")
            if (jar?.protocol == "jar") {
                val url = PicUtils::class.java.protectionDomain.codeSource.location
                try {
                    var filePath = URLDecoder.decode(url.path, "UTF-8")
                    if (filePath.endsWith(".jar")) { // 可执行jar包运行的结果里包含".jar"
                        ext = "jar"
                        // 截取路径中的jar包名
                        filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1)
                    }
                    //                System.out.println(filePath);
                    file = File(filePath)
                } catch (e: UnsupportedEncodingException) {
//			e.printStackTrace();
//                Logger.getLogger(PicUtils.class).error(e.getMessage());
                    file = File(System.getProperty("user.dir"))
                }
            } else {
                file = File(System.getProperty("user.dir"))
            }
            //        System.out.println(file.getPath());
            return file
        }

    /**
     * 授权
     *
     * @param tempFile 授权文件
     */
    fun authorization(tempFile: Path) {
        if (isWindow()) return
        val builder = ProcessBuilder("/bin/chmod", "755", tempFile.pathString)
        try {
            val process = builder.start()
            val rc = process.waitFor()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun isWindow(): Boolean {
        return System.getProperty("os.name").lowercase().startsWith("win")
    }


}
